<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <div slot="detail">
      <a-form-model ref="form" :model="model" :rules="validatorRules" >
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="调研标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
              <a-input v-model="model.title" placeholder="请输入调研标题"></a-input>
            </a-form-model-item>
          </a-col>
          <draggable @end="(event) => end(event, researchContent)" :options="{ animation: 300 }" :list="researchContent">
            <template v-for="(group, groupIndex) in researchContent">
              <a-col :span="24">
                <a-card :bordered="false" style="padding: 0 10%;">
                  <div slot="title">
                    <a-input
                      placeholder="问卷组标题"
                      style="width: 45.8%;"
                      v-show="group.subtitle.editing"
                      v-model="group.subtitle.value"
                      :ref="`groupTitle${groupIndex}`"
                      @blur="() => group.subtitle.editing = false"
                      @keyup.enter="() => group.subtitle.editing = false"
                    />
                    <a-space v-show="!group.subtitle.editing" style="cursor: pointer;" @click="() => focus(groupIndex)">
                      <span>{{ group.subtitle.value }}</span>
                      <a-icon type="edit"/>
                    </a-space>
                    <a-icon
                      type="delete"
                      style="color: rgba(0,0,0,.45); position: absolute; right: 14.5%; top: 25px; cursor: pointer;"
                      @click="() => deleteArray(researchContent, groupIndex)"/>
                  </div>
                  <a-row>
                    <draggable
                      @start="start"
                      @end="(event) => end(event, group.problems)"
                      @add="(event) => draggableAdd(event, group.problems)"
                      :options="{ animation: 300 }"
                      :list="group.problems"
                      :group="groupIndex === 0 ? { name: 'problems', pull: pullFunction } : 'problems'"
                    >
                      <template v-for="(problem, problemIndex) in group.problems">
                        <a-col :span="24" style="margin-bottom: 15px;">
                          <a-input
                            v-model="problem.topic"
                            :ref="`problemTopic${groupIndex}-${problemIndex}`"
                            :addon-before="problem.sort + 1"
                          >
                            <a-tooltip slot="suffix" v-show="group.problems.length > 1">
                              <a-icon
                                type="close-circle"
                                style="color: rgba(0,0,0,.45)"
                                @click="() => deleteArray(group.problems, problemIndex)"
                              />
                            </a-tooltip>
                          </a-input>
                          <div v-if="problem.type === 0" style="padding: 10px 12% 0 12%;">
                            <draggable
                              @end="(event) => end(event, problem.options)"
                              :options="{ animation: 300 }"
                              :list="problem.options"
                            >
                              <template v-for="(option, optionIndex) in problem.options">
                                <a-row style="padding: 5px 0">
                                  <a-col :span="22">
                                    <a-input
                                      v-model="option.value"
                                      :ref="`optionValue${groupIndex}-${problemIndex}-${optionIndex}`"
                                      :addon-before="alphabet[optionIndex]">
                                      <a-tooltip slot="suffix" v-show="problem.options.length > 2">
                                        <a-icon
                                          type="close-circle"
                                          style="color: rgba(0,0,0,.45)"
                                          @click="() => deleteArray(problem.options, problemIndex)"
                                        />
                                      </a-tooltip>
                                    </a-input>
                                  </a-col>
                                  <a-col :span="2" v-if="optionIndex === 0" style="top: 3px; left: 15px;">
                                    <a-button type="dashed" shape="circle" icon="plus" size="small" @click="() => addOption(problem.options, groupIndex, problemIndex)"/>
                                  </a-col>
                                </a-row>
                              </template>
                            </draggable>
                          </div>
                        </a-col>
                      </template>
                    </draggable>
                    <a-col :span="11">
                      <a-button type="dashed" style="width: 100%" @click="() => addProblem(group.problems, 1, groupIndex)">
                        <a-icon type="plus" />问答题
                      </a-button>
                    </a-col>
                    <a-col :span="2" />
                    <a-col :span="11">
                      <a-button type="dashed" style="width: 100%" @click="() => addProblem(group.problems, 0, groupIndex)">
                        <a-icon type="plus" />选择题
                      </a-button>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
            </template>
          </draggable>

          <div style="padding: 0 42%;">
            <a-button type="primary" style="width: 100%; margin-top: 25px;" shape="round" @click="addGroup">
              <a-icon type="plus" />问卷组
            </a-button>
          </div>
        </a-row>
      </a-form-model>
      </div>
    </j-form-container>
  </a-spin>
</template>

<script>
  import draggable from 'vuedraggable'
  import { httpAction, getAction } from '@/api/manage'
  export default {
    name: 'MartResearchForm',
    components: {
      draggable
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model:{},
        researchContent: [],
        controlOnStart: true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        alphabet: ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
        confirmLoading: false,
        validatorRules: {
          title: [
            { required: true, message: '请输入调研问卷标题'}
          ]
        },
        url: {
          add: "/martResearch",
          edit: "/martResearch",
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      addGroup() {
        let sort = this.researchContent.length
        this.researchContent.push({
          subtitle: {
            value: '',
            editing: true
          },
          problems: []
        })
        setTimeout(() => {
          this.$refs[`groupTitle${sort}`][0].focus()
        }, 100)
      },
      addProblem(problems, type, groupIndex) {
        let sort = problems.length
        let problem = {
          topic: '',
          type,
          sort
        }
        if (type === 0) {
          problem.options = [{
            value: '',
            sort: 0
          }, {
            value: '',
            sort: 1
          }]
        }
        problems.push(problem)
        setTimeout(() => {
          this.$refs[`problemTopic${groupIndex}-${sort}`][0].focus()
        }, 100)
      },
      addOption(options, groupIndex, problemIndex) {
        let sort = options.length
        options.push({ value: '', sort })
        setTimeout(() => {
          this.$refs[`optionValue${groupIndex}-${problemIndex}-${sort}`][0].focus()
        }, 100)
      },
      deleteArray(array, index) {
        array.splice(index, 1);
        this.sureChange(array)
      },
      focus(index) {
        this.researchContent[index].subtitle.editing = true
        setTimeout(() => {
          this.$refs[`groupTitle${index}`][0].focus()
        }, 100)
      },
      start({ originalEvent }) {
        this.controlOnStart = originalEvent.ctrlKey;
      },
      end(event, array) {
        /*console.log("拖动前的位置" + event.oldIndex);
        console.log("拖动后的位置" + event.newIndex);*/
        this.sureChange(array)
      },
      sureChange(array){
        for(let i = 0; i < array.length; i++) {
          array[i].sort = i;
        }
      },
      draggableAdd(event, array) {
        this.sureChange(array)
      },
      pullFunction() {
        return this.controlOnStart ? "clone" : true;
      },
      add () {
        this.visible = true;
        this.addGroup()
      },
      edit (record) {
        this.model = Object.assign({}, record);
        if (this.model.researchContent) {
          this.researchContent = this.stringToObject(this.model.researchContent)
        }
        this.visible = true;
      },
      stringToObject(contentString) {
        if (!contentString) return []
        let contentJSON = JSON.parse(contentString)
        if (!contentJSON) return []
        for (let i = 0; i < contentJSON.length; i++) {
          let subtitleText = contentJSON[i].subtitle
          contentJSON[i].subtitle = { value: subtitleText, editing: false }
          for (let j = 0; j < contentJSON[i].problems.length; j++) {
            contentJSON[i].problems[j].sort = j
            if (contentJSON[i].problems[j].type === 0) {
              for (let k = 0; k < contentJSON[i].problems[j].options.length; k++) {
                let optionText = contentJSON[i].problems[j].options[k]
                contentJSON[i].problems[j].options[k] = { value: optionText, sort: k}
              }
            }
          }
        }
        return contentJSON
      },
      objectToString(contentObject) {
        if (!contentObject || contentObject.length === 0) return '[]'
        let object = []
        for (let i = 0; i < contentObject.length; i++) {
          let subtitleText = contentObject[i].subtitle.value
          object.push({ subtitle: subtitleText, problems: [] })
          for (let j = 0; j < contentObject[i].problems.length; j++) {
            object[i].problems.push({
              topic: contentObject[i].problems[j].topic,
              type: contentObject[i].problems[j].type
            })
            if (contentObject[i].problems[j].type === 0) {
              object[i].problems[j].options = []
              for (let k = 0; k < contentObject[i].problems[j].options.length; k++) {
                let optionText = contentObject[i].problems[j].options[k].value
                object[i].problems[j].options.push(optionText)
              }
            }
          }
        }
        return JSON.stringify(object)
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.researchContent = this.objectToString(this.researchContent)
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>